//
//  NewFirmwareUpdateViewController.m
//  INMOTION
//
//  Created by cjg on 2020/3/3.
//  Copyright © 2020 Inmotion. All rights reserved.
//

#import "NewFirmwareUpdateViewController.h"
#import "IMTConfig.h"
#import "IMFunction.h"
#import "IMNewCarModel.h"
#import "NSObject+HUD.h"
#import "KSLanguageManager.h"
#import "IMTCommonWebView.h"
#import "KSBLEManager.h"
#import "IMTCANManager.h"
#import "IMTHTTPSessionManager.h"

@interface NewFirmwareUpdateViewController ()<WKNavigationDelegate>
{
    // 单次上传文件的大小
    NSUInteger packetSize;
    // 固件升级包重试次数
    NSUInteger repSendCount;
}
@property (weak, nonatomic) IBOutlet UILabel *versionLB;
@property (weak, nonatomic) IBOutlet UILabel *fileSizeLB;
@property (weak, nonatomic) IBOutlet UIProgressView *firmwareProgressView;
@property (weak, nonatomic) IBOutlet UILabel *firmwareProgressNumLB;
@property (weak, nonatomic) IBOutlet IMTCommonWebView *contentWebView;
@property (weak, nonatomic) IBOutlet UIButton *updateBtn;
@property (weak, nonatomic) IBOutlet UILabel *lastTimeLB;

@property (assign, nonatomic) CGFloat contentWebViewHeight;
@property (nonatomic , assign) BOOL isUpdating;
// 固件升级下标
@property (nonatomic , assign) uint32_t sendingIndex;

@property (nonatomic , assign) BOOL isCancle;
@property (nonatomic , assign) BOOL isShowContent;

// 当前文件句柄
@property (nonatomic , assign) uint8_t handle;
@property (nonatomic , assign) double startTransportDate;


@property (nonatomic, strong) UITapGestureRecognizer *tap;

@end

@implementation NewFirmwareUpdateViewController

- (LXFirmwareModel *)firmwareModel {
    if (!_firmwareModel) {
        _firmwareModel = [[LXFirmwareModel alloc] init];
    }
    return _firmwareModel;
}

- (void)back {
    if (self.isUpdating) {
        
        [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_can_not_interrupt_upgrading")];
        return;
        
        UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:IMTNewCarLocalizedString(@"The firmware is being upgraded, are you sure you want to stop the update?") preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *ok = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"activity_diagnose_stop") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            self.isCancle = YES;
            [self.carModel.l9_CarModel closeFileWithHandle:self.handle compleBlock:^(NSError *error, NSData *responseData) {
                // 关闭文件不处理关闭文件失败
                uint8_t handle;
                [responseData getBytes:&handle range:NSMakeRange(0, 1)];
                uint8_t errorCode ;
                [responseData getBytes:&errorCode range:NSMakeRange(1, 1)];
                if (self.isFromCarHome) {
                    [[KSBLEManager sharedManager] disconnect];
                }
                if (self.navigationController.viewControllers.count == 1) {
                    [self dismissViewControllerAnimated:true completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:true];
                }
            }];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_cancel") style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [ac addAction:ok];
        [ac addAction:cancel];
        [self presentViewController:ac animated:YES completion:nil];
    }else {
        if (self.isFromCarHome) {
            [[KSBLEManager sharedManager] disconnect];
        }
        if (self.navigationController.viewControllers.count == 1) {
            [self dismissViewControllerAnimated:true completion:nil];
        } else {
            [self.navigationController popViewControllerAnimated:true];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self dismissHUD];
    self.isCancle = YES;
    [self.navigationController.navigationBar removeGestureRecognizer:self.tap];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(navTap:)];
    self.tap.numberOfTapsRequired = 5;
    [self.navigationController.navigationBar addGestureRecognizer:self.tap];
}

- (void)navTap:(UITapGestureRecognizer *)tap {
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:IMTNewCarLocalizedString(@"prompt_input_upgrade_code") message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [ac addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = IMTNewCarLocalizedString(@"prompt_input_upgrade_code");
    }];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"activity_change_bt_pwd_btn_text") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UITextField *field = ac.textFields[0];
        [self getServerCarVersionMessageWithCode:field.text];
    }];
    UIAlertAction *Cancel = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_cancel") style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
    }];
    [ac addAction:confirm];
    [ac addAction:Cancel];
    [self presentViewController:ac animated:YES completion:nil];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = IMTNewCarLocalizedString(@"car_feature_fw_upgrade");
    [self.updateBtn setTitle:IMTNewCarLocalizedString(@"btn_upgrade") forState:(UIControlStateNormal)];

    self.contentWebViewHeight = 44;
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back_white"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = left;
    
    packetSize = 200;
    repSendCount = 0;
    self.sendingIndex = 0;
    self.isCancle = NO;
    self.isUpdating = NO;
    self.updateBtn.enabled = NO;
    self.isShowContent = NO;
    [self updateConfigView:NO];
    
    if (self.firmwareModel.level > 0) {
        self.isUpdating = YES;
        [self.carModel.l9_CarModel setCarNeedUploadWithRank:self.firmwareModel.level lowest:self.firmwareModel.minVersion highest:self.firmwareModel.maxVersion successBlock:^{
            NSLog(@"写入成功");
        } failBlock:^(NSError *error) {
            NSLog(@"写入失败");
        }];
        
        [self updateConfigView:YES];
        [self updateAction:self.updateBtn];
    } else {
        // 读取当前固件版本号
        [self.carModel.l9_CarModel getCarVersionSuccessBlock:^{
            [self getServerCarVersionMessageWithCode:@""];
        } failBlock:^(NSError *error) {
        }];
    }
    
}

// 请求服务器固件版本
- (void)getServerCarVersionMessageWithCode:(NSString *)code {
    [self showProgressHUDWithText:nil];
    NSDictionary *parame = @{@"sn":self.carModel.l9_CarModel.lx_sn,@"carType":self.carModel.l9_CarModel.LX_CarType,@"version":self.carModel.l9_CarModel.versionData,@"upgradeCode":code};
    // 请求当前固件版本
    [[IMTHTTPSessionManager sharedInstance] ks_POST:@"checkOemFwUpgrade" parameters:parame success:^(NSURLSessionDataTask *task, id responseObject) {
        [self dismissHUD];
        if (responseObject) {
            [self.firmwareModel loadDataFromResponseData:responseObject];
            if (self.firmwareModel.fileUrl) {
                [self updateConfigView:YES];
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self showErrorHUDWithText:nil];
    }];
}

- (void)updateConfigView:(BOOL)isNeedUpdate {
        
    if (isNeedUpdate) {
        self.versionLB.text = self.firmwareModel.version;
        self.fileSizeLB.hidden = NO;
        self.updateBtn.enabled = YES;
        self.fileSizeLB.text = [NSString stringWithFormat:@"%ldKB",[self.firmwareModel.fileSize integerValue]/1000];
        self.contentWebView.navigationDelegate = self;
        [self.contentWebView loadHTMLString:self.firmwareModel.descriptionText baseURL:nil];
        self.contentWebView.scrollView.scrollEnabled = NO;
    }else {
        self.versionLB.text = IMTNewCarLocalizedString(@"prompt_no_new_version");
        self.fileSizeLB.hidden = YES;
        self.updateBtn.enabled = NO;
    }
    [self.tableView reloadData];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0 && self.isShowContent) {
        return 2;
    }else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 1) {
        return self.contentWebViewHeight;
    }
    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

// 显示车辆当前版本号
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return [NSString stringWithFormat:@"%@:%@",IMTNewCarLocalizedString(@"prompt_current_version"),self.carModel.l9_CarModel.carVersion];
    }
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return nil;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) {
        cell.contentView.frame = cell.bounds;
    }
}

// 固件升级按钮
- (IBAction)updateAction:(UIButton *)sender {
    [self showProgressHUDWithText:IMTNewCarLocalizedString(@"prompt_downloading")];
    [[IMTHTTPSessionManager sharedInstance] LXDownloadFileFromUrl:self.firmwareModel.fileUrl filePath:@"firmware.bin" progress:^(CGFloat progress) {
        
    } success:^(NSURL *filePath) {
        self.firmwareModel.firmwareData = [NSData dataWithContentsOfURL:filePath];//[NSData dataWithContentsOfFile:filePath.absoluteString];
        if (self.firmwareModel.firmwareData) {
            [self dismissHUD];
            if (IMTCarSeriesLorin(self.carModel.carType)) {
                [self start];
            }
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            self.updateBtn.enabled = NO;
        }else {
            [self showErrorHUDWithText:IMTNewCarLocalizedString(@"firmware_abnormal")];
            self.updateBtn.enabled = YES;
        }
    } failure:^(NSError *error) {
        [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_download_failed")];
        self.updateBtn.enabled = YES;
    }];
}

#pragma mark ====== WebViewDelegate  网页代理
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    [webView evaluateJavaScript:@"document.documentElement.scrollHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        CGFloat webHeight = [result floatValue];
        NSLog(@"网页高度： === %f",webHeight);
        if (webHeight > self.contentWebViewHeight) {
            self.contentWebViewHeight = webHeight + 20;
        }
        [self.tableView reloadData];
    }];
}

#pragma mark ====== 固件升级
// 第一步 -- 启动固件升级
- (void)start {
    [self.carModel.l9_CarModel writeCarUploadOpenOrCloseWithParam:1 successBlock:^{
        [self showSuccessHUDWithText:nil];
        [self openFile];
    } failBlock:^(NSError *error) {
        if (error.code == 3) {
            [self showErrorHUDWithText:IMTNewCarLocalizedString(@"Please hold the vehicle still and try again")];
        }else {
            [self showErrorHUDWithText:[NSString stringWithFormat:@"%@（3,4,%ld)",IMTNewCarLocalizedString(@"prompt_upgrade_failed"),(long)error.code]];
        }
    }];
}

// 第二步 -- 打开文件
- (void)openFile {
    WS(weakSelf);
    self.firmwareProgressView.hidden = NO;
    self.lastTimeLB.hidden = NO;
    self.firmwareProgressNumLB.hidden = NO;
    NSData *fileData = self.firmwareModel.firmwareData;
    [self.carModel.l9_CarModel openFileWithType:2 fileName:@"update.bin\0\0" compleBlock:^(NSError *error, NSData *responseData) {
        if (error) {
            [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@（4,1,%ld)",IMTNewCarLocalizedString(@"prompt_upgrade_failed"),(long)error.code]];
            return ;
        }
        if (responseData.length < 10) {
            [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@（4,1,0,-1)",IMTNewCarLocalizedString(@"prompt_upgrade_failed")]];
            return ;
        }
        // 句柄
        uint8_t handle;
        [responseData getBytes:&handle range:NSMakeRange(0, 1)];
        weakSelf.handle = handle;
        // 错误码
        uint8_t errorCode ;
        [responseData getBytes:&errorCode range:NSMakeRange(1, 1)];
        // 已存在文件大小
        uint32_t fifleSize ;
        [responseData getBytes:&fifleSize range:NSMakeRange(2, 4)];
        // 已存在文件的校验
        uint32_t checkValue ;
        [responseData getBytes:&checkValue range:NSMakeRange(6, 4)];
        // 文件修改日期 - 无用
        if (responseData.length >= 14) {
            uint32_t time ;
            [responseData getBytes:&time range:NSMakeRange(10, 4)];
            time = [IMFunction change:time];
            uint8_t year = (time & 0xfc000000) >> 26;
            uint8_t month = (time & 0x03c00000) >> 22;
            uint8_t day = (time & 0x003e0000) >> 17;
            uint8_t shi = (time & 0x0001f000) >> 12;
            uint8_t fen = (time & 0x00000fc0) >> 6;
            uint8_t miao = time & 0x0000003f;
            NSLog(@"文件的更新日期 ：%d年%d月%d日 %d:%d:%d",year,month,day,shi,fen,miao);
        }
        
        if (errorCode == 0) {
            if (fifleSize > 0) { // 已存在部分文件-断点续传
                if (fifleSize > fileData.length) {
                    weakSelf.startTransportDate = [[NSDate date] timeIntervalSince1970];
                    weakSelf.sendingIndex = 0;
                    [weakSelf writeDataToDeviceWithHandel:handle data:fileData num:0];
                }else {
                    NSData *hasData = [fileData subdataWithRange:NSMakeRange(0, fifleSize)];
                    uint32_t check = [weakSelf.carModel.l9_CarModel crc32CheckWithData:hasData];
                    uint32_t allcheck = [weakSelf.carModel.l9_CarModel crc32CheckWithData:fileData];
                    NSLog(@"文件的校验值 ====已有大小:%u -- 固件大小:%lu========= 已存在check🔥%u = 本地存在check🔥%u = 固件check🔥%u",fifleSize,(unsigned long)fileData.length,checkValue,check,allcheck);
                    
                    if (checkValue == check) {
                        weakSelf.startTransportDate = [[NSDate date] timeIntervalSince1970];
                        weakSelf.sendingIndex = fifleSize;
                        [weakSelf writeDataToDeviceWithHandel:handle data:fileData num:0];
                    }else {
                        weakSelf.startTransportDate = [[NSDate date] timeIntervalSince1970];
                        weakSelf.sendingIndex = 0;
                        [weakSelf writeDataToDeviceWithHandel:handle data:fileData num:0];
                    }
                }
            }else {
                weakSelf.startTransportDate = [[NSDate date] timeIntervalSince1970];
                weakSelf.sendingIndex = 0;
                [weakSelf writeDataToDeviceWithHandel:handle data:fileData num:0];
            }
        }else {
            [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@（4,1,%d)",IMTNewCarLocalizedString(@"prompt_upgrade_failed"),errorCode]];
        }
    }];
}

// 第三步 -- 写入文件
- (void)writeDataToDeviceWithHandel:(uint8_t)handel data:(NSData *)allData num:(int)num{
    if (self.isCancle) {
        self.isUpdating = NO;
        [self dismissHUD];
        return;
    }
    num ++;
    
    self.isUpdating  = YES;
    // 要上传的文件数据
    NSData *fileData = allData;
    NSUInteger dataLength = allData.length;
    
    if (self.sendingIndex < dataLength) {
        // 发送数据包的长度
        NSUInteger sendAmount = dataLength - self.sendingIndex;
        if (sendAmount >= packetSize) {
            sendAmount = packetSize;
        }
        NSData *sendingData = [fileData subdataWithRange:NSMakeRange(self.sendingIndex, sendAmount)];
        [self.carModel.l9_CarModel writeFileWithHandle:handel offset:self.sendingIndex data:sendingData compleBlock:^(NSError *error, NSData *responseData) {
            if (!error) {
                uint8_t handle;
                [responseData getBytes:&handle range:NSMakeRange(0, 1)];
                uint8_t errorCode ;
                [responseData getBytes:&errorCode range:NSMakeRange(1, 1)];
                uint8_t hasWriteLength;
                [responseData getBytes:&hasWriteLength range:NSMakeRange(2, 1)];
                if (errorCode == 0) {
                    self.sendingIndex = self.sendingIndex + (uint32_t)sendAmount;
                    NSLog(@"⏫完成 ======== index:%u",self.sendingIndex);
                    
                    CGFloat p = (CGFloat)self.sendingIndex;
                    CGFloat progress = p/fileData.length;
                    
                    double nowDate = [[NSDate date] timeIntervalSince1970];
                    // 计算两个时间差值确定已传输的速度
                    NSInteger timeInterval = nowDate - self.startTransportDate;
                    NSString *pro = nil;
                    if (timeInterval && self.sendingIndex) {
                        NSInteger speed = self.sendingIndex / timeInterval;
                        NSInteger lastTime = (fileData.length - self.sendingIndex) / speed;
                        NSLog(@"下载进度⏬ ⏬ ⏬ ============== %ld",(long)lastTime);
                        pro = [NSString stringWithFormat:@"%@:%ld%@%d%@",IMTNewCarLocalizedString(@"The remaning time"),lastTime/60,IMTNewCarLocalizedString(@"min"),lastTime%60,IMTNewCarLocalizedString(@"sec")];
                    }
                    NSLog(@"下载进度⏬ ==============%@",pro);
                    self.lastTimeLB.text = pro;
                    self.firmwareProgressView.progress = progress;
                    self.firmwareProgressNumLB.text = [NSString stringWithFormat:@"%.2f%%",progress*100];
                    [self writeDataToDeviceWithHandel:handel data:allData num:0];
                }else {
                    // 如果是消息出错如超时造成的重试则延时重试
                    if (num > 3) {
                        self.isUpdating = NO;
                        [self showErrorHUDWithText:[NSString stringWithFormat:@"%@ (4,2,%d)",IMTNewCarLocalizedString(@"prompt_upgrade_failed"),errorCode]];
                        return;
                    }
                    [self writeDataToDeviceWithHandel:handel data:allData num:num];
                }
            }else {
                self.isUpdating = NO;
                [self showErrorHUDWithText:[NSString stringWithFormat:@"%@ (4,2,%ld)",IMTNewCarLocalizedString(@"prompt_upgrade_failed"),(long)error.code]];
            }
        }];
    }else { // 上传完成检验总文件
        uint32_t checkValue = [self.carModel.l9_CarModel crc32CheckWithData:allData];
        uint32_t size = (uint32_t)allData.length;
        [self checkFileWithHandle:handel fileSize:size index:size checkValue:checkValue];
    }
}

// 第四步 -- 校验文件
- (void)checkFileWithHandle:(uint8_t)handle fileSize:(uint32_t)filesize index:(uint32_t)index checkValue:(uint32_t)checkValue {
    
    [self showProgressHUDWithText:nil];
    self.isUpdating  = NO;
    // 文件句柄 、 文件总大小、 指定偏移地址、 指定偏移地址处的校验值
    [self.carModel.l9_CarModel writeFileCheckWithHandle:handle fileSize:filesize offset:index checkCrc32:checkValue compleBlock:^(NSError *error, NSData *responseData) {
        NSLog(@"%@ - ====文件校验结果==== - %@",error,responseData);
        if (error) {
            [self showErrorHUDWithText:[NSString stringWithFormat:@"%@ (4,3,%ld)",IMTNewCarLocalizedString(@"prompt_upgrade_failed"),(long)error.code]];
            return ;
        }
        if (responseData.length < 3) {
            [self showErrorHUDWithText:[NSString stringWithFormat:@"%@ (4,3,0,-1)",IMTNewCarLocalizedString(@"prompt_upgrade_failed")]];
            return ;
        }
        uint8_t handle;
        [responseData getBytes:&handle range:NSMakeRange(0, 1)];
        uint8_t errorCode ;
        [responseData getBytes:&errorCode range:NSMakeRange(1, 1)];
        uint8_t checkCode ;
        [responseData getBytes:&checkCode range:NSMakeRange(2, 1)];
        if (errorCode == 0) {
            if (checkCode == 1) {
                [self closeFlieWithHandle:handle];
            }else {
                [self showErrorHUDWithText:[NSString stringWithFormat:@"%@（4,3,0,%d)",IMTNewCarLocalizedString(@"prompt_upgrade_failed"),checkCode]];
            }
        }else {
            [self showErrorHUDWithText:[NSString stringWithFormat:@"%@（4,3,%d)",IMTNewCarLocalizedString(@"prompt_upgrade_failed"),checkCode]];
        }
    }];
}

// 第五步 -- 关闭文件
- (void)closeFlieWithHandle:(uint8_t)handle {
    [self.carModel.l9_CarModel closeFileWithHandle:handle compleBlock:^(NSError *error, NSData *responseData) {
        if (error) {
            [self showErrorHUDWithText:[NSString stringWithFormat:@"%@（4,4,%ld)",IMTNewCarLocalizedString(@"prompt_upgrade_failed"),(long)error.code]];
            return ;
        }
        NSLog(@"%@ - ====关闭文件结果==== - %@",error,responseData);
        uint8_t handle;
        [responseData getBytes:&handle range:NSMakeRange(0, 1)];
        uint8_t errorCode ;
        [responseData getBytes:&errorCode range:NSMakeRange(1, 1)];
        if (errorCode == 0) {
            self.sendingIndex = 0;

            UIAlertController *vc = [UIAlertController alertControllerWithTitle:nil message:IMTNewCarLocalizedString(@"prompt_can_not_interrupt_upgrading") preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_ok") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                [[IMTCANManager sharedInstance] clearMessages];
                [[KSBLEManager sharedManager] disconnect];
                [self.navigationController popToRootViewControllerAnimated:true];
            }];
            [vc addAction:sure];
            [self presentViewController:vc animated:YES completion:nil];
            
//            [self showSuccessHUDWithText:IMTNewCarLocalizedString(@"prompt_can_not_interrupt_upgrading")];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////                if (self.navigationController.viewControllers.count == 1) {
////                    [self dismissViewControllerAnimated:true completion:nil];
////                } else {
////                    [self.navigationController popViewControllerAnimated:true];
////                }
//
//                [[IMTCANManager sharedInstance] clearMessages];
//                [[KSBLEManager sharedManager] disconnect];
//                [self.navigationController popToRootViewControllerAnimated:true];
//            });
        }else {
            [self showErrorHUDWithText:[NSString stringWithFormat:@"%@（4,4,%d)",IMTNewCarLocalizedString(@"prompt_upgrade_failed"),errorCode]];
        }
    }];
}

// 第六步 -- 终止升级 -- 暂时没用
- (void)endFileUpdate {
    [self.carModel.l9_CarModel writeCarUploadOpenOrCloseWithParam:0 successBlock:^{
        [self showSuccessHUDWithText:IMTNewCarLocalizedString(@"prompt_upgrade_succeed")];
    } failBlock:^(NSError *error) {
        [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_upgrade_failed")];
    }];
}

@end
